package base.thread_JUC2.chapter04.demo06;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor pool = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

        System.out.printf("Main: Starting at: %s\n",new Date());
        // 创建一个周期性执行的任务:延时1s开启任务，之后每隔2s执行一次(如果每个任务自身执行耗时在2s以上，你会发现同时会存在两个任务)
        Task task = new Task("任务");
        ScheduledFuture<?> scheduledFuture = pool.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);

        // 随便输出20次，观察观察距离下次任务执行剩余时间，并休眠500ms
        for (int i = 0; i < 20; i++) {
            System.out.println("距离下一任务开始执行，还剩："+scheduledFuture.getDelay(TimeUnit.MILLISECONDS) +"毫秒. 执行任务总数："+pool.getTaskCount());
            TimeUnit.MILLISECONDS.sleep(500);
        }

        pool.shutdown();// 结束执行器

        // 等待5s让周期性任务全部执行完成
        TimeUnit.SECONDS.sleep(5);
        System.out.printf("Main: Finished at: %s\n",new Date());
    }
}
